import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config} from '../../shared/smartadmin.config';

declare var $: any;
declare var echarts: any;
@Component({
	selector: 'sa-plantArea-daily',
	templateUrl: './plantArea-daily.component.html',
})
export class PlantAreaDailyComponent implements OnInit {
	tableData:any= []; //table数据
	startTime:string=''; //开始时间
	endTime:string=''; //结束时间
	selectedCompanyId:string = ''; //公司ID
	selectedCompanyName:string = ''; //公司名称
	carNumber:string = '';
	sortBy:string = '0';
	sortType:string = '1';
	quantityType:string = '';
	userName: string = '' //上传人员
	constructor(private jsonApiService: JsonApiService, private router: Router,private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
//			this.curPage = queryParams.nowPage == undefined? 1:queryParams.nowPage;
		});
	}
	ngOnInit() {
		this.initDate().then(()=>{
		    this.load();
		});
	}
	ngOnDestroy(){
		document.onclick = null;
	}

	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({//时间插件
							format: "yyyy-mm-dd",
						    language: "zh-CN",
						    autoclose: true,
						    minView: 2,
						}).on("changeDate", function(e){
							var date = e.date;
							var time = common.getTimeMmss(date);
							var timeToDay = new Date().toLocaleDateString().replace("/","-");
							$("#datetimepicker1").datetimepicker("setEndDate", $('#datetimepicker2').val()+' 23:59:59');
							$("#datetimepicker2").datetimepicker("setStartDate", time);
							$("#datetimepicker2").datetimepicker("setEndDate", timeToDay);
						});
						$("#datetimepicker2").datetimepicker({//时间插件
							format: "yyyy-mm-dd",
						    language: "zh-CN",
						    autoclose: true,
						    minView: 2,
						}).on("changeDate", function(e){
							var date = e.date;
							var time = common.getTimeMmss(date);
							var timeToDay = new Date().toLocaleDateString().replace("/","-");
							$("#datetimepicker1").datetimepicker("setEndDate", time);
							$("#datetimepicker2").datetimepicker("setEndDate", timeToDay);
							$("#datetimepicker2").datetimepicker("setStartDate", $('#datetimepicker1').val()+' 00:00:00');
							// $("#datetimepicker1").datetimepicker("setEndDate", timeToDay);
							// $("#datetimepicker1").datetimepicker("setEndDate", time);
						});
						let nowDate = common.getNowTime().split(' ')[0];
						$("#datetimepicker1").val(nowDate);
						$("#datetimepicker2").val(nowDate);
						resolve();
					});
				}
			);
		})
	}
	//清除所选时间
	del_date(){
		this.startTime = '';
		this.endTime = '';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	// 排序change
	@ViewChild('sortSelect') sortSelect: ElementRef;
	sortChange(){
		let sortSelectDom = this.sortSelect.nativeElement,
			selectedIndex = sortSelectDom.selectedIndex,
			sortBy = sortSelectDom.options[selectedIndex].dataset.sort,
			sortType = sortSelectDom.options[selectedIndex].dataset.type;
		this.sortBy = sortBy;
		this.sortType = sortType;
	}
	// 数据导出
	exportData(){		
	    this.startTime = $('#datetimepicker1').val();
        this.endTime = $('#datetimepicker2').val();
        if(!this.startTime || !this.endTime){
            this.jsonApiService.message('时间范围不能为空');
            return;
        }
		const param = {			
			companyId: this.selectedCompanyId,
            startTime:this.startTime + ' 00:00:00',
            endTime:this.endTime + ' 23:59:59',
            sortBy: this.sortBy,
            sortType: this.sortType,
			quantityType: this.quantityType,
			userName: this.userName
		}				
		common.exprotDataFile(param, 'param', config.BaseURL + 'factoryDaily/exportProjectDailyData.html')	
	}
	//表格搜索
	table_search() {
		this.load();
	}
	//刷新
	refresh(){
    	this.load();
    }
	//初始化加载list数据
	load() {
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		if(!this.startTime || !this.endTime){
			this.jsonApiService.message('时间范围不能为空');
			return;
		}
		let tableSearch = {
            parameters:{
                companyId:this.selectedCompanyId,
                startTime:this.startTime + ' 00:00:00',
                endTime:this.endTime + ' 23:59:59',
                sortBy:this.sortBy,
                sortType:this.sortType,
				quantityType: this.quantityType,
				userName: this.userName
            }
        }
        let reqdata = 'gridPager='+JSON.stringify(tableSearch);
		this.jsonApiService.http("factoryDaily/list.html", reqdata).subscribe(data => {
			if(data.success){
				var result = data.data;
				for(let item of result) {
				    item.installedRatio =  item.expectedNum ? (item.totalNum*100 / item.expectedNum).toFixed(2)+'%' :'';
				    item.alertFlag = false;
				    // if(item.fieldEquipment < 5){
				    //     item.alertFlag = true;
				    // }
				    // if(item.peopleNumber){
				    //     if(item.installedNum / item.peopleNumber < 3){
                    //         item.alertFlag = true;
                    //     }
				    // }
				}
				this.tableData = result;
			}
		})
}
	// 删除
	delRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("factoryDaily/deletedById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message)
				if(data.success){
                    this.load();
                }
			})
		})
	}
	// 编辑表单数据
	projectDailyFrom:any = {
	    id: '',
	    companyName: '',
	    companyId: '',
	    installationSituation: '',
	    installedNum: '',
	    repairsNum: '',
	    maintenanceMatters: '',
	    fieldEquipmentSan: '',
		fieldEquipmentDai: '',
		weather: '',
		userName: '',
		userId:'',
		sensorNum: '',
		pedestalNum: '',
		powerWireNum: '',
		eightWireNum: '',
		tenWireNum: ''
	}
	// 编辑
	editRow(row) {
	    $('#projectDailyModal').modal('show');
	    for(let key in this.projectDailyFrom){
	        this.projectDailyFrom[key] = row[key];
	    }
	}
	// 编辑取消
	projectDailyCancel() {
	    $('#projectDailyModal').modal('hide');
	}
	// 编辑提交
	projectDailySubmit() {
	    this.jsonApiService.http_obj("factoryDaily/update.html", this.projectDailyFrom).subscribe(data => {
            this.jsonApiService.message(data.message);
            if(data.success){
                this.load();
                this.projectDailyCancel();
            }
        })
	}
	itemPageForm:any = {
	    title:'代维人员',
	    key:'maintenanceStaff',
	}
	// 单项编辑
	editItemPage(title,key,row){
	    for(let key in this.projectDailyFrom){
            this.projectDailyFrom[key] = row[key];
        }
	    $('#itemModal').modal('show');
	    this.itemPageForm.title = title;
	    this.itemPageForm.key = key;
	}
	// 单项编辑取消
	itemModalClose(){
	    $('#itemModal').modal('hide');
	}
	// 单项数据提交
	itemModalSubmit(){
	    if(this.itemPageForm.key == 'fieldEquipmentSan' || this.itemPageForm.key == 'fieldEquipmentDai' || this.itemPageForm.key == 'peopleNumber' || this.itemPageForm.key == 'onlineNumber'){
	        if(isNaN(this.projectDailyFrom[this.itemPageForm.key])){
	            this.jsonApiService.message('请输入数字格式');
	            return;
	        }
	    }
	    this.jsonApiService.http_obj("factoryDaily/update.html", this.projectDailyFrom).subscribe(data => {
            this.jsonApiService.message(data.message);
            if(data.success){
                this.load();
                this.itemModalClose();
            }
        })
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}
	// 页面跳转
	jumpPage(Url,row){
	    row.startTime = this.startTime + ' 00:00:00';
	    row.endTime = this.endTime + ' 23:59:59';
	    let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
        common.setCookie('jumpTo'+Url, JSON.stringify(row));
        window.open(BaseURL+'#'+Url);
	}
}